#include "tcpserverui.h"
//使用iostream可以做一些调试
#include <iostream>
using namespace std;

//TcpServerUI构造函数
TcpServerUI::TcpServerUI(QWidget *parent)
    : QDialog(parent)
{
    //serWindowTitle()是QObject的方法，设置标题
    //tr()也是OBject的方法，可以将char *转化为QString
    setWindowTitle(tr("TCP Server"));

    //声明各个控件
    contentListWidget = new QListWidget;
    portLabel = new QLabel(tr("端口："));
    portLineEdit = new QLineEdit;
    createServerBtn = new QPushButton(tr("创建聊天室"));

    mainGridLayout = new QGridLayout(this);

    //使用mainGridlayout构造UI
    mainGridLayout->addWidget(contentListWidget, 0, 0, 1, 2);
    mainGridLayout->addWidget(portLabel, 1, 0);
    mainGridLayout->addWidget(portLineEdit, 1, 1);
    mainGridLayout->addWidget(createServerBtn, 2, 0, 1, 2);

    //默认端口8010，也可以不设置
    port = 8010;
    //在portLineEdit设置内容为port
    portLineEdit->setText(QString::number(port));

    //connect createServerBtn的clicked()信号和Server的slotCreateServer()槽
    connect(createServerBtn, SIGNAL(clicked()), this, SLOT(slotCreateServer()));
}

//当createServerBtn发出clicked()的信号时，信号传递到slotCreateServer槽
void TcpServerUI::slotCreateServer()
{
//    createServerBtn->setEnabled(false);

    //获取portLineEdit的端口值，转化为int
    int tmp = portLineEdit->text().toInt();
    if(!(tmp < 1024 || portLineEdit->text() == ""))
        port = tmp;
    cout<<"server port:"<<port<<endl;

    //构造Server
    server = new Server(this, port);

    //绑定Server的updateServer信号和TcpServerUI的updateServer槽
    connect(server, SIGNAL(updateServer(QString, int)),
            this, SLOT(updateServer(QString, int)));

    //调用createServerBtn的sertEnabled方法，使button无法被点击
    createServerBtn->setEnabled(false);
}

//当Server的updateServer信号发出时，updateServer槽获取信号，执行槽内代码
void TcpServerUI::updateServer(QString msg, int length)
{
    contentListWidget->addItem(msg.left(length));
}

TcpServerUI::~TcpServerUI()
{

}
